package main

import (
	"fmt"
	"io"
	"log"
	"net"
	"os"
	"sort"
	"strings"
)

func main() {
	// demo1()
	// demo2()
	demo8()
}

func demo1() {
	conn1, err := net.Dial("tcp", "127.0.0.1:8080")
	fmt.Println(conn1, err)

	conn2, _ := net.Dial("tcp", "127.0.0.1:8080")
	fmt.Println(conn2)
}

func demo2() {
	a := 1
	fmt.Println(&a)
	b := &a
	fmt.Println(*b)
}

func demo3() {
	num := 10
	modifyFromPoint(num)
	fmt.Println("未使用指针：", num)

	num1 := 20
	newModifyFromPoint(&num1)
	fmt.Println("使用指针：", num1)
}

func modifyFromPoint(num int) {
	num = 100
	fmt.Println("未使用指针，方法内:", num)
}

func newModifyFromPoint(ptr *int) {
	*ptr = 1000 // 修改指针地址指向的值
	fmt.Println("使用指针，方法内:", *ptr)
}

func demo4() {
	for y := 1; y <= 9; y++ {
		// 遍历, 决定这一行有多少列
		for x := 1; x <= y; x++ {
			fmt.Printf("%d*%d=%d ", x, y, x*y)
		}
		// 手动生成回车
		fmt.Println()
	}
}

type Cat struct{}
type Dog struct{}

func (c Cat) Say() string { return "喵喵喵" }
func (d Dog) Say() string { return "汪汪汪" }
func demo5() {
	c := Cat{}
	fmt.Println("猫:", c.Say())
	d := Dog{}
	fmt.Println("狗:", d.Say())
}

func demo6() {
	reader := strings.NewReader("mszlu test123 123")
	// 每次读取4个字节
	p := make([]byte, 4)
	for {

		n, err := reader.Read(p)
		if err != nil {
			if err == io.EOF {
				log.Printf("读完了:eof错误 :%d", n)
				break
			}
			log.Printf("其他错误:%v", err)
			os.Exit(2)
		}
		log.Printf("[读取到的字节数为:%d][内容:%v]", n, string(p[:n]))
	}

}

func demo7() {
	myMap := map[string]int{
		"apple":  5,
		"banana": 3,
		"orange": 7,
		"grape":  1,
	}

	keys := make([]string, 0, len(myMap))
	for key := range myMap {
		keys = append(keys, key)
	}

	sort.Strings(keys)

	for _, key := range keys {
		fmt.Printf("%s: %d\n", key, myMap[key])
	}
}

func demo8() {
	for i := 0; i < 5; i++ {
		defer func() {
			fmt.Println(i)
		}()
	}
}
